<template>
  <div class="user-management">
    <el-card>
      <template #header>
        <div class="card-header">
          <h2>用户管理</h2>
          <el-button type="primary" @click="openUserDialog()">新增用户</el-button>
        </div>
      </template>

      <el-table :data="userList" border style="width: 100%">
        <el-table-column prop="id" label="ID" width="80"></el-table-column>
        <el-table-column prop="userName" label="用户名"></el-table-column>
        <el-table-column prop="phone" label="手机号"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="gender" label="性别" width="80">
          <template #default="scope">
            {{ scope.row.gender === 0 ? '男' : '女' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button type="primary" size="small" @click="openUserDialog(scope.row)">编辑</el-button>
            <el-button type="danger" size="small" @click="deleteUser(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        layout="prev, pager, next"
        :total="total"
        :page-size="pageSize"
        :current-page="currentPage"
        @current-change="handlePageChange"
      ></el-pagination>
    </el-card>

    <!-- 用户编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="isEdit ? '编辑用户' : '新增用户'" width="50%">
      <el-form :model="userForm" label-width="100px">
        <el-form-item label="用户名">
          <el-input v-model="userForm.userName" placeholder="请输入用户名"></el-input>
        </el-form-item>

        <el-form-item label="手机号码">
          <el-input v-model="userForm.phone" placeholder="请输入手机号码"></el-input>
        </el-form-item>

        <el-form-item label="邮箱">
          <el-input v-model="userForm.email" placeholder="请输入邮箱"></el-input>
        </el-form-item>

        <el-form-item label="性别">
          <el-radio-group v-model="userForm.gender">
            <el-radio :label="0">男</el-radio>
            <el-radio :label="1">女</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="密码" v-if="!isEdit">
          <el-input v-model="userForm.password" type="password" placeholder="请输入密码"></el-input>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveUser">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { listUser, getUser, addUser, updateUser, delUser } from '@/api/user'

// 用户列表
const userList = ref([])

// 分页参数
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 对话框显示状态
const dialogVisible = ref(false)

// 是否为编辑模式
const isEdit = ref(false)

// 用户表单
const userForm = reactive({
  id: null,
  userName: '',
  phone: '',
  email: '',
  gender: 0,
  password: ''
})

// 获取用户列表
const getUserList = async () => {
  try {
    const res = await listUser()
    userList.value = res.data || []
    total.value = res.total || 0
  } catch (error) {
    console.error('获取用户列表失败', error)
    ElMessage.error('获取用户列表失败')
  }
}

// 打开用户对话框
const openUserDialog = (user) => {
  if (user) {
    // 编辑模式
    isEdit.value = true
    Object.assign(userForm, user)
  } else {
    // 新增模式
    isEdit.value = false
    // 重置表单
    Object.assign(userForm, {
      id: null,
      userName: '',
      phone: '',
      email: '',
      gender: 0,
      password: ''
    })
  }

  dialogVisible.value = true
}

// 保存用户
const saveUser = async () => {
  try {
    if (isEdit.value) {
      // 编辑用户
      await updateUser(userForm)
      ElMessage.success('用户更新成功')
    } else {
      // 新增用户
      await addUser(userForm)
      ElMessage.success('用户添加成功')
    }

    // 关闭对话框
    dialogVisible.value = false

    // 刷新用户列表
    getUserList()
  } catch (error) {
    console.error('保存用户失败', error)
    ElMessage.error('保存用户失败')
  }
}

// 删除用户
const deleteUser = (user) => {
  ElMessageBox.confirm(`确定要删除用户 ${user.userName} 吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      try {
        await delUser(user.id)
        ElMessage.success('用户删除成功')
        getUserList()
      } catch (error) {
        console.error('删除用户失败', error)
        ElMessage.error('删除用户失败')
      }
    })
    .catch(() => {})
}

// 页码变化
const handlePageChange = (page) => {
  currentPage.value = page
  getUserList()
}

// 初始化
onMounted(() => {
  getUserList()
})
</script>
